Passed
Pull Request — master (#19)
by Muhammad Dyas
01:35
created

ActionHandler.closePoll   A

Complexity

Conditions 2

Size

Total Lines 15
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 15
rs 9.7
c 0
b 0
f 0
cc 2
1
import {chat_v1 as chatV1} from 'googleapis/build/src/apis/chat/v1';
2
import BaseHandler from './BaseHandler';
3
import NewPollFormCard from '../cards/NewPollFormCard';
4
import {addOptionToState, getConfigFromInput, getStateFromCard} from '../helpers/state';
5
import {callMessageApi} from '../helpers/api';
6
import {createDialogActionResponse, createStatusActionResponse} from '../helpers/response';
7
import PollCard from '../cards/PollCard';
8
import {ClosableType, MessageDialogConfig, PollFormInputs, PollState, taskEvent, Voter} from '../helpers/interfaces';
9
import AddOptionFormCard from '../cards/AddOptionFormCard';
10
import {saveVotes} from '../helpers/vote';
11
import {PROHIBITED_ICON_URL} from '../config/default';
12
import ClosePollFormCard from '../cards/ClosePollFormCard';
13
import MessageDialogCard from '../cards/MessageDialogCard';
14
import {createTask} from '../helpers/task';
15
16
/*
17
This list methods are used in the poll chat message
18
 */
19
interface PollAction {
20
  saveOption(): Promise<chatV1.Schema$Message>;
21
22
  getEventPollState(): PollState;
23
}
24
25
export default class ActionHandler extends BaseHandler implements PollAction {
26
  async process(): Promise<chatV1.Schema$Message> {
27
    const action = this.event.common?.invokedFunction;
28
    switch (action) {
29
      case 'start_poll':
30
        return await this.startPoll();
31
      case 'vote':
32
        return this.recordVote();
33
      case 'add_option_form':
34
        return this.addOptionForm();
35
      case 'add_option':
36
        return await this.saveOption();
37
      case 'show_form':
38
        const pollForm = new NewPollFormCard({topic: '', choices: []}, this.getUserTimezone()).create();
39
        return createDialogActionResponse(pollForm);
40
      case 'new_poll_on_change':
41
        return this.newPollOnChange();
42
      case 'close_poll_form':
43
        return this.closePollForm();
44
      case 'close_poll':
45
        return await this.closePoll();
46
      default:
47
        return createStatusActionResponse('Unknown action!', 'UNKNOWN');
48
    }
49
  }
50
51
  /**
52
   * Handle the custom start_poll action.
53
   *
54
   * @returns {object} Response to send back to Chat
55
   */
56
  async startPoll() {
57
    // Get the form values
58
    const formValues: PollFormInputs = this.event.common!.formInputs! as PollFormInputs;
59
60
    const config = getConfigFromInput(formValues);
61
62
    if (!config.topic || config.choices.length === 0) {
63
      // Incomplete form submitted, rerender
64
      const dialog = new NewPollFormCard(config, this.getUserTimezone()).create();
65
      return createDialogActionResponse(dialog);
66
    }
67
    if (config.closedTime) {
68
      // because previously we marked up the time with user timezone offset
69
      config.closedTime -= this.getUserTimezone()?.offset ?? 0;
70
    }
71
    const pollCardMessage = new PollCard({author: this.event.user, ...config}).createMessage();
72
73
    const request = {
74
      parent: this.event.space?.name,
75
      requestBody: pollCardMessage,
76
    };
77
    const apiResponse = await callMessageApi('create', request);
78
    if (apiResponse.data?.name) {
79
      if (config.autoclose && config.closedTime) {
80
        const taskPayload: taskEvent = {'id': apiResponse.data.name, 'action': 'close_poll', 'type': 'TASK'};
81
        await createTask(JSON.stringify(taskPayload), config.closedTime);
82
      }
83
      return createStatusActionResponse('Poll started.', 'OK');
84
    } else {
85
      return createStatusActionResponse('Failed to start poll.', 'UNKNOWN');
86
    }
87
  }
88
89
  /**
90
   * Handle the custom vote action. Updates the state to record
91
   * the user's vote then rerenders the card.
92
   *
93
   * @returns {object} Response to send back to Chat
94
   */
95
  recordVote() {
96
    const parameters = this.event.common?.parameters;
97
    if (!(parameters?.['index'])) {
98
      throw new Error('Index Out of Bounds');
99
    }
100
    const choice = parseInt(parameters['index']);
101
    const userId = this.event.user?.name ?? '';
102
    const userName = this.event.user?.displayName ?? '';
103
    const voter: Voter = {uid: userId, name: userName};
104
    const state = this.getEventPollState();
105
106
    // Add or update the user's selected option
107
    state.votes = saveVotes(choice, voter, state.votes!, state.anon);
108
    const card = new PollCard(state);
109
    return {
110
      thread: this.event.message?.thread,
111
      actionResponse: {
112
        type: 'UPDATE_MESSAGE',
113
      },
114
      cardsV2: [card.createCardWithId()],
115
    };
116
  }
117
118
  /**
119
   * Opens and starts a dialog that allows users to add details about a contact.
120
   *
121
   * @returns {object} open a dialog.
122
   */
123
  addOptionForm() {
124
    const state = this.getEventPollState();
125
    const dialog = new AddOptionFormCard(state).create();
126
    return createDialogActionResponse(dialog);
127
  };
128
129
  /**
130
   * Handle add new option input to the poll state
131
   * the user's vote then rerenders the card.
132
   *
133
   * @returns {object} Response to send back to Chat
134
   */
135
  async saveOption(): Promise<chatV1.Schema$Message> {
136
    const userName = this.event.user?.displayName ?? '';
137
    const state = this.getEventPollState();
138
    const formValues = this.event.common?.formInputs;
139
    const optionValue = formValues?.['value']?.stringInputs?.value?.[0]?.trim() || '';
140
    addOptionToState(optionValue, state, userName);
141
142
    const cardMessage = new PollCard(state).createMessage();
143
144
    const request = {
145
      name: this.event.message!.name,
146
      requestBody: cardMessage,
147
      updateMask: 'cardsV2',
148
    };
149
    const apiResponse = await callMessageApi('update', request);
150
    if (apiResponse.status === 200) {
151
      return createStatusActionResponse('Option is added', 'OK');
152
    } else {
153
      return createStatusActionResponse('Failed to add option.', 'UNKNOWN');
154
    }
155
  }
156
157
  getEventPollState(): PollState {
158
    const stateJson = getStateFromCard(this.event);
159
    if (!stateJson) {
160
      throw new ReferenceError('no valid state in the event');
161
    }
162
    return JSON.parse(stateJson);
163
  }
164
165
  async closePoll(): Promise<chatV1.Schema$Message> {
166
    const state = this.getEventPollState();
167
    state.closedTime = Date.now();
168
    const cardMessage = new PollCard(state).createMessage();
169
    const request = {
170
      name: this.event.message!.name,
171
      requestBody: cardMessage,
172
      updateMask: 'cardsV2',
173
    };
174
    const apiResponse = await callMessageApi('update', request);
175
    if (apiResponse.status === 200) {
176
      return createStatusActionResponse('Poll is closed', 'OK');
177
    } else {
178
      return createStatusActionResponse('Failed to close poll.', 'UNKNOWN');
179
    }
180
  }
181
182
  closePollForm() {
183
    const state = this.getEventPollState();
184
    if (state.type === ClosableType.CLOSEABLE_BY_ANYONE || state.author!.name === this.event.user?.name) {
185
      return createDialogActionResponse(new ClosePollFormCard().create());
186
    }
187
188
    const dialogConfig: MessageDialogConfig = {
189
      title: 'Sorry, you can not close this poll',
190
      message: `The poll setting restricts the ability to close the poll to only the creator(${state.author!.displayName}).`,
191
      imageUrl: PROHIBITED_ICON_URL,
192
    };
193
    return createDialogActionResponse(new MessageDialogCard(dialogConfig).create());
194
  }
195
196
  newPollOnChange() {
197
    const formValues: PollFormInputs = this.event.common!.formInputs! as PollFormInputs;
198
    const config = getConfigFromInput(formValues);
199
    return createDialogActionResponse(new NewPollFormCard(config, this.getUserTimezone()).create());
200
  }
201
}
202